package rpg.ai.pathFinder;

import java.util.ArrayList;
import java.util.Random;

import rpg.map.Location;

/**
 * 
 * @author Pedro Silva Moreira
 */
public class APathFinder extends PathFinder {
	private Random random = new Random();

	// Creation
	public APathFinder() {
	}

	// Path
	@Override
	public ArrayList<Location> pathTo(Location from, Location to, boolean one,
			boolean escape) {
		if (escape)
			one = true;

		ArrayList<Location> result = new ArrayList<Location>();
		while (true) {
			int distance = from.distance(to, true);
			if (!escape && distance <= 1) {
				if (distance == 0 || distance == 1 && !to.walkAble())
					break;
			}

			int x = from.getX();
			int y = from.getY();
			int z = from.getZ();

			ArrayList<Location> directions = new ArrayList<Location>();
			for (int i = -1; i <= 1; i++) {
				for (int j = -1; j <= 1; j++) {
					if (i == 0 && j == 0)
						continue;

					Location loc = from.getMap().getLocation(x + i, y + j, z);

					if (loc == null || !loc.walkAble()) {
						continue;
					}

					directions.add(loc);
				}
			}

			Location best = null;
			Integer margin = null;
			for (Location it : directions) {
				int g = from.distance(it, false) == 1 ? 10 : 14;
				if(it.containsItemType("special") != null)
					g += 8;
				
				int h = to.distance(it, false) * 10;
				int f = g + h;

				if (margin == null || f == margin || (!escape && f < margin)
						|| (escape && f > margin) || (escape && random.nextInt(4) == 0)) {
					if (margin == null || f != margin || random.nextInt(2) == 0) {
						best = it;
						margin = f;
					}
				}
			}

			if (best != null) {
				result.add(best);

				if (one) {
					break;
				}

				from = best;
			} else {
				break;
			}
		}
		return result;
	}
}
